<?php
namespace App\Http\Controllers\Order;

use App\Http\Controllers\Controller;
use App\Models\Order\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Agent\ChaoZongdai;

class OrderController extends Controller
{
    public function index(Request $request) {

        if ($request->ajax()) {

            $rows = $request->get("rows");

            $acc = Order::join("users", "orders.user_id", "=", "users.id")
                ->join("goods", "orders.goods_id", "=", "goods.id")
                ->select(DB::raw("
                orders.id AS `orders.id`,
                user_id,
                bindid,
                orders.zongdai AS `zongdai`,
                lottery_value,
                res,
                nickname,
                orders.time AS `orders.time`,
                number,
                goods.name AS `goods.name`,
                orders.discount_type,
                `type`,
                num,
                win,
                amounts,
                status"));

            
            $acc = $this->filters($request, $acc);

            if($request->get("ids")) {
                $acc = $acc->orwhereIn('orders.id',explode(",", $request->get("ids")));
            }
            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $acc = $acc->where('orders.chao_zongdai',$chaoz->id);
            }
            if ($request->get("user_id")) {
                $acc = $acc->where("user_id", $request->get("user_id"));
            }

            $paginator = $acc->orderBy($request->get("sidx"), $request->get("sord"))->paginate($rows);

            $rows = [];
            foreach ($paginator as $page) {

                $page->mount = $page->num * $page->amounts;
                if ($page->type == 0) {
                    $json = json_decode($page->res, true);
                    $n = 0;
                    foreach ($json as $key => $v2) {
                        $n += count($v2);
                    }
                    $page->mount *= $n;
                }
                $rows[] = $page;
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view("order/order/index", ["user_id" => $request->get("user_id")]);
        }
    }
}
